package com.zxd.interview.jmm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 不适用的第二种场景
 */
public class NoVolatile2 implements Runnable{

    volatile boolean a;

    AtomicInteger realA = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        NoVolatile2 noVolatile2 = new NoVolatile2();
        Thread thread1 = new Thread(noVolatile2);
        thread1.start();
        Thread thread2 = new Thread(noVolatile2);
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("noVolatile.a => "+ noVolatile2.a);
        System.out.println("AtomicInteger.realA => "+ noVolatile2.realA.get());


    }/**

     这里不适用，noVolatile.a 可能为 true 或者 false
     noVolatile.a => true
     AtomicInteger.realA => 2000

     noVolatile.a => false
     AtomicInteger.realA => 2000
     */


    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            // 无限翻转，依赖之前的状态
            a = !a;
            realA.incrementAndGet();
        }
    }
}
